//
//  ZNewBuiltViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/2/21.
//  Copyright © 2017年 zjq. All rights reserved.
//

typedef NS_ENUM(NSInteger,CellType){
    
    CellTypeWithDefualt = 0,
    CellTypeWithAge,
    CellTypeWithPhoneNumber
};
#import "ZNewBuiltViewController.h"

#import "ZNewBuiltTableViewCell.h"
#import "ZHealhMidTableViewCell.h"
#import "ZHealthBottomTableViewCell.h"
#import "ZHealhTopTableViewCell.h"


#import "LZSelectSexView.h" // 性别选择
#import "LZSelectView.h" // 头像选择
#import "JTTakeAlbumOrCamera.h"

#import "ZCullingViewController.h"

#import "LPopChangView.h"

static NSString * const KNBBuiltTableViewCellIdentifier = @"KNBBuiltTableViewCellIdentifier";
static NSString * const KNBHealhTopTableViewCellIdentifier = @"KNBHealhTopTableViewCellIdentifier";
static NSString * const KNBHealhMidTableViewCellIdentifier = @"KNBHealhMidTableViewCellIdentifier";
static NSString * const KNBZHealthBottomTableViewCellIdentifier = @"KNBZHealthBottomTableViewCellIdentifier";
@interface ZNewBuiltViewController ()<UITableViewDelegate,UITableViewDataSource,pointOutDelegate,selectSexDelegate> {
    UITableView * _mainTableView;
    NSArray * _titleName;
    NSMutableArray * _contentext;
    NSArray * _styleName;
    LZUserInfo * userInfo;
    UIButton * _makeNewBtn;
    // 新建档案
    UIImage *newIcon;
    NSString *newTitle;
    NSString *newSex;
    NSString *newAge;
}
@property (nonatomic,strong)LZSelectView * iconSelectView; //选择头像
@property (nonatomic,strong) LZSelectSexView * selectSexView;//选择性别
@property (nonatomic,strong) LPopChangView * lPopChangView;
@end

@implementation ZNewBuiltViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialzeDatas];
    [self initlizeInterface];
}

- (void)initialzeDatas {
    _titleName = @[@"名称",@"性别",@"年龄"];
    _contentext = [@[@"填写档案名称",@"选择性别",@"填写年龄"] mutableCopy];
    _styleName = @[@"发病部位照片",@"病例报告照片",@"X光照片"];
    userInfo = [LZUserInfo getUserInfo];
}

- (void)initlizeInterface {
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"新建档案";
    _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, SCREEN_Height-64*ysIZE) style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    _mainTableView.sectionFooterHeight = 0;
    _mainTableView.sectionHeaderHeight = 0;
    _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_mainTableView registerClass:[ZHealhMidTableViewCell class] forCellReuseIdentifier:KNBHealhMidTableViewCellIdentifier];
    [_mainTableView registerClass:[ZHealthBottomTableViewCell class] forCellReuseIdentifier:KNBZHealthBottomTableViewCellIdentifier];
    [_mainTableView registerClass:[ZHealhTopTableViewCell class] forCellReuseIdentifier:KNBHealhTopTableViewCellIdentifier];
    [_mainTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"nothing"];
    //创建footView
    UIView * footView = [[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_Width, 70*ysIZE)];
    footView.backgroundColor = KHColorFromRGB(0xf8f8f8);
    _makeNewBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_makeNewBtn setBackgroundColor:MYGREENColor];
    [_makeNewBtn setTitle:@"新建" forState:UIControlStateNormal];
    [_makeNewBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _makeNewBtn.frame = CGRectMake(20*xsIZE, 20*ysIZE, 280*xsIZE, 45*ysIZE);
    [_makeNewBtn addTarget:self action:@selector(makeNewBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:_makeNewBtn];
    _mainTableView.tableFooterView = footView;
    [self.view addSubview:_mainTableView];
}

// 表格视图协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return 3;
    }else if (section == 2) {
        return 4;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 60*ysIZE;
    }else if (indexPath.section == 1) {
        return 65*ysIZE;
    }else if (indexPath.section ==2) {
        if (indexPath.row == 0 ) {
            return 45*ysIZE;
        }else{
            return 90*ysIZE;
        }
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
   
    return 10*ysIZE;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZHealhTopTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:KNBHealhTopTableViewCellIdentifier forIndexPath:indexPath];
        cell.titlelabel.text = @"头像";
//        cell.headImageView.image = [UIImage imageNamed:@"data_tx_140"];
        cell.headImageView.image = newIcon ? newIcon: [UIImage imageNamed:@"data_tx_140"];
        return cell;
    }else if (indexPath.section == 1) {
        ZHealhMidTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:KNBHealhMidTableViewCellIdentifier forIndexPath:indexPath];
        cell.titleName.text = _titleName[indexPath.row];
        cell.bottomLabel.text = _contentext[indexPath.row];
        return cell;
    }else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            ZHealhTopTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:KNBHealhTopTableViewCellIdentifier forIndexPath:indexPath];
            cell.headImageView.hidden = YES;
            cell.titlelabel.text = @"发病部位照片";
            return cell;
        }else {
            ZHealthBottomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:KNBZHealthBottomTableViewCellIdentifier forIndexPath:indexPath];
            cell.styleLabel.text = _styleName[indexPath.row-1];
            cell.numberLabel.text = @"0张照片";
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        }
    }
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"nothing" forIndexPath:indexPath];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        [self ejectIconView];
        return;
    }else if (indexPath.section ==1 && indexPath.row == 1){
        [self ejectsexView];
        return;
    }else if (indexPath.section == 2&& !(indexPath.row == 0)) {
        ZCullingViewController * ZCVC = [[ZCullingViewController alloc] init];
        [self.navigationController pushViewController:ZCVC animated:YES];
        return;
    }else if (indexPath.section == 1&& indexPath.row == 0) {
        [self changItemWithName:@"填写档案名称" indexPath:indexPath keyBoradType:UIKeyboardTypeDefault cellType:CellTypeWithDefualt];
    }else if (indexPath.section == 1 && indexPath.row ==  2) {
        [self changItemWithName:@"修改年龄" indexPath:indexPath keyBoradType:UIKeyboardTypeNumberPad cellType:CellTypeWithAge];
    }
    return;
}
// 弹窗修改 年龄和名字
- (void)changItemWithName:(NSString *)itemName indexPath:(NSIndexPath *)indexPath keyBoradType:(UIKeyboardType)type cellType:(CellType)cellType {
    LPopChangView *changeView = [[LPopChangView alloc] initWithFrame:self.navigationController.view.bounds AndTitle:[NSString stringWithFormat:@"%@",itemName] type:type];
    [self.navigationController.view addSubview:changeView];
    
    __weak typeof(changeView) weakChangeView = changeView;
    changeView.InputContentBlock = ^(NSString *inputContent){
        if (!inputContent.length) {
            [YJProgressHUD showMessage:@"输入不能为空" inView:self
             .navigationController.view];
            return;
        }
        
        switch (indexPath.row) {
            case 0:
                // 健康档案名称
                newTitle = inputContent;
                break;
            case 1:
                // 性别
                
                break;
            case 2:
                // 年龄
                newAge = inputContent;
                break;
                
            default:
                break;
        }
        
        //        // 判断年龄
        if (cellType == CellTypeWithAge) {
            
            NSInteger age = [inputContent integerValue];
            if (age <= 0 || age >= 100) {
                [YJProgressHUD showMessage:@"年龄输入有误" inView:self.navigationController.view];
                return;
            }
            // 发送请求
        }
        
        ZHealhMidTableViewCell * cell = [_mainTableView cellForRowAtIndexPath:indexPath];
        
        cell.bottomLabel.text = inputContent;
        [weakChangeView removeFromSuperview];
        
    };
}

// 弹出选择头像界面的方法
- (void)ejectIconView {
    [self.view endEditing:YES];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.iconSelectView];
}

- (void)ejectsexView {
    [self.view endEditing:YES];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.selectSexView];
    
}
// 选择头像来选的方法
- (void)SelectCellIndexPath:(NSInteger)cellSection index:(NSInteger)cellIndex {
    if (cellSection == 0&&cellIndex==0) {
        [JTTakeAlbumOrCamera takeAlbumWithViewcontroller:self withID:self];
        return;
    }else if (cellSection == 0 && cellIndex == 1) {
        [JTTakeAlbumOrCamera takeCameraWithViewcontroller:self withID:self];
        return;
    }else{
        
        return;
    }
}

// 拿到照片的回调方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    // UIImagePickerControllerOriginalImage 原始图片
    // UIImagePickerControllerEditedImage 编辑后图片
    newIcon = info[UIImagePickerControllerEditedImage];
    //[self saveImage:icon withName:@"currentImage.png"];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [_mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    // 换头像以后网络请求
    //[self requestWithIcon:icon];
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
}


// 选择性别的方法
- (void)selectSEX:(NSString *)sex cellIndex:(NSInteger)cellIndex {
    if (cellIndex == 1 ) {
        [self.selectSexView removeFromSuperview];
        return;
    }
    newSex = sex;
    [_contentext replaceObjectAtIndex:1 withObject:sex];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:1];
    [_mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}
//lazy
- (LZSelectSexView *)selectSexView {
    if (_selectSexView) {
        return _selectSexView;
    }
    _selectSexView = [[LZSelectSexView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, SCREEN_Height)];
    _selectSexView.pointDeleGate = self;
    return _selectSexView;
}

- (LZSelectView *)iconSelectView {
    if (_iconSelectView) {
        return _iconSelectView;
    }
    _iconSelectView = [[LZSelectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, SCREEN_Height)];
    _iconSelectView.pointDeleGate = self;
    return _iconSelectView;
}

// 新建按钮点击
- (void)makeNewBtnClick {
    LZLog(@"新建");
    if (!newIcon) {
        [YJProgressHUD showMessage:@"头像不可以为空" inView:self.view];
        return;
    }if (!newTitle) {
        [YJProgressHUD showMessage:@"名称不可以为空" inView:self.view];
        return;
    }
    if (!newSex) {
        [YJProgressHUD showMessage:@"性别不可以为空" inView:self.view];
        return;
    }
    if (!newAge) {
        [YJProgressHUD showMessage:@"年龄不可以为空" inView:self.view];
        return;
    }
    // 关闭按钮的交互
    _makeNewBtn.userInteractionEnabled = NO;
    NSDictionary *paramas = @{@"uid":userInfo.uid,@"title":newTitle,@"sex":newSex,@"age":newAge};
    NSMutableDictionary *dict1 = [NSMutableDictionary dictionaryWithObject:newIcon forKey:@"pic"];
    __weak typeof(self) weakSelf = self;
    [BaseRequest requestWithMethodForFile:TestURL paramars:paramas paramarsSite:@"File/addFile" fileDict:dict1 progressBlock:nil successBlock:^(id content) {
        [YJProgressHUD showProgress:@"创建中..." inView:self.view];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"-------新建健康档案数据----------%@",dict);
        if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"创建失败" inView:self.view];
        }else if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"创建成功" inView:self.view];
            [weakSelf creatSucceedAndBack];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"创建失败" inView:self.view];
    }];
}

// 创建成功以后返回上个界面
- (void)creatSucceedAndBack {
    
    if (self.delegate && [self.delegate conformsToProtocol:@protocol(ZNewBuiltViewControllerDelegate)]) {
        [self.delegate refreshUI];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _makeNewBtn.userInteractionEnabled = YES;
        [self.navigationController popViewControllerAnimated:YES];
    });

}



@end
